package com.example.mcdonaldapplication.fragment

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.mcdonaldapplication.R
import com.example.mcdonaldapplication.databinding.FragmentMeBinding
import com.example.mcdonaldapplication.info.GoodsInfo
import com.example.mcdonaldapplication.info.ServerIP
import com.example.mcdonaldapplication.info.TicketInfo
import com.example.mcdonaldapplication.info.UserInfo
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import kotlin.concurrent.thread

class MeFragment : Fragment(),View.OnClickListener {
    private var _binding: FragmentMeBinding? = null
    private val binding get() = _binding!!
    private lateinit var info:UserInfo
    private val serverIP = ServerIP.getIp()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        _binding = FragmentMeBinding.inflate(inflater, container, false)
        getUser()

        //登录
        val btnLogin = binding.btnLogin
        btnLogin.setOnClickListener{
            val navController = findNavController()
            navController.navigate(R.id.action_navigation_me_to_loginActivity)
        }
        //个人页面
        val imageUser = binding.imageUserHead
        imageUser.setOnClickListener{
            val navController = findNavController()
            navController.navigate(R.id.action_navigation_me_to_userActivity)
        }
        //退出登录
        val llLogout = binding.llLogout
        llLogout.setOnClickListener(this)

        //钱包
        val llWallet = binding.llWallet
        llWallet.setOnClickListener{
            val navController = findNavController()
            navController.navigate(R.id.action_navigation_me_to_walletActivity)
        }
        //条款
        val llRule = binding.llRule
        llRule.setOnClickListener{
            val navController = findNavController()
            navController.navigate(R.id.action_navigation_me_to_ruleActivity)
        }
        //建议
        val llAdvice = binding.llAdvice
        llAdvice.setOnClickListener{
            val navController = findNavController()
            navController.navigate(R.id.action_navigation_me_to_adviceActivity)
        }
        //地址
        val llAddress = binding.llAddress
        llAddress.setOnClickListener{
            if(!getUser()){
                val navController = findNavController()
                navController.navigate(R.id.action_navigation_me_to_loginActivity)
            }
            else{
                val navController = findNavController()
                navController.navigate(R.id.action_navigation_me_to_userAddressActivity)
            }
        }
        //订单
        val llAllOrder = binding.llAllOrder
        llAllOrder.setOnClickListener{
            if(!getUser()){
                val navController = findNavController()
                navController.navigate(R.id.action_navigation_me_to_loginActivity)
            }
            else{
                val navController = findNavController()
                navController.navigate(R.id.action_navigation_me_to_userAllOrderActivity)
            }
        }
        //二维码付款
        val btnCharge = binding.btnCharge
        btnCharge.setOnClickListener{
            val navController = findNavController()
            navController.navigate(R.id.action_navigation_me_to_QRcodeActivity)
        }
        //到店券 外送券
        val llOrderTicket = binding.llOrderTicket
        llOrderTicket.setOnClickListener{
            val navController = findNavController()
            navController.navigate(R.id.action_navigation_me_to_walletActivity)
        }
        val llTakeawayTicket = binding.llTakeawayTicket
        llTakeawayTicket.setOnClickListener{
            val navController = findNavController()
            navController.navigate(R.id.action_navigation_me_to_walletActivity)
        }
        //赠送券
        val llGiveTicket = binding.llGiveTicket
        llGiveTicket.setOnClickListener{
            val navController = findNavController()
            navController.navigate(R.id.action_navigation_me_to_walletActivity)
        }
        //兑换券
        val llExchangeTicket = binding.llExchangeTicket
        llExchangeTicket.setOnClickListener{
            val navController = findNavController()
            navController.navigate(R.id.action_navigation_me_to_exchangeTicketActivity)
        }

        return binding.root
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.llLogout -> {
                AlertDialog.Builder(activity).apply {
                    setMessage("是否退出?")
                    setCancelable(false)
                    setPositiveButton("是") { _, _ ->
                        thread {
                            val prefs = requireActivity().getSharedPreferences("user", Context.MODE_PRIVATE).edit()
                            prefs.clear()
                            prefs.apply()
                            onResume()
                        }
                    }
                    setNegativeButton("否") { _, _ ->
                    }
                    show()
                }
            }
        }
    }

    private fun getUser():Boolean{
        val tvUsername = binding.tvUsername
        val tvIntegral = binding.tvIntegral
        val tvBalance = binding.tvBalance
        var prefs = requireActivity().getSharedPreferences("user", Context.MODE_PRIVATE)
        val uid = prefs.getInt("uid", 0)
        getUserFromNetwork(uid)
        prefs = requireActivity().getSharedPreferences("user", Context.MODE_PRIVATE)
        val username = prefs.getString("username", "")
        val integral = prefs.getInt("integral", 0).toString()
        val balance = prefs.getString("balance", "0.0")
        if(username != ""){
            tvUsername.text = "$username"
            tvIntegral.text = integral
            tvBalance.text = "$balance"
            val llNotLogin = binding.llNotLogin
            val llLogin = binding.llLogin
            llNotLogin.visibility = View.GONE
            llLogin.visibility = View.VISIBLE
//            getTicket()
            thread {
                var orderTicketNum = 0
                var giveTicketNum = 0
                var takeawayTicketNum = 0
                val formBody: FormBody = FormBody.Builder()
                    .add("uid", uid.toString())
                    .build()
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://${serverIP}/ticket/queryAll")
                    .post(formBody)
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body.string()
                val gson = Gson()
                val jsonObject = JSONObject(responseData)
                val data = jsonObject.getString("data")
                val message = jsonObject.getString("message")
                if(message == "优惠券为空"){
                    orderTicketNum = 0
                    giveTicketNum = 0
                    takeawayTicketNum = 0
                }else{
                    val typeOf = object : TypeToken<List<TicketInfo>>() {}.type
                    val ticketInfoList = gson.fromJson<List<TicketInfo>>(data, typeOf)
                    for (ticket in ticketInfoList) {
                        if(ticket.type == "0"){
                            orderTicketNum+=1
                        }else if(ticket.type == "1"){
                            takeawayTicketNum+=1
                        }
                        giveTicketNum+=1
                    }
                }
                requireActivity().runOnUiThread {
                    binding.tvOrderTicketNum.text = "$orderTicketNum"
                    binding.tvGiveTicketNum.text = "$giveTicketNum"
                    binding.tvTakeawayTicketNum.text = "$takeawayTicketNum"
                }
            }
            return true
        } else {
            requireActivity().runOnUiThread{
                val llNotLogin = binding.llNotLogin
                val llLogin = binding.llLogin
                llNotLogin.visibility = View.VISIBLE
                llLogin.visibility = View.GONE
            }
            return false
        }
    }

    private fun getUserFromNetwork(uid: Int){
        thread{
            val formBody: FormBody = FormBody.Builder()
                .add("id", uid.toString())
                .build()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://${serverIP}/user/query")
                .post(formBody)
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body.string()
            Log.d("responseData",response.toString())
            parseJsonUser(responseData)
        }
    }

    @SuppressLint("CommitPrefEdits")
    private fun parseJsonUser(json: String){
        val jsonObject = JSONObject(json)
        val data = jsonObject.getJSONObject("data")

//        Log.d("goods",goods.toString())
//        Log.d("good", data.get(i).toString())
        val editor = requireActivity().getSharedPreferences("user", Context.MODE_PRIVATE).edit()
        val uid = data.optString("uid").toInt()
        val username = data.optString("username").toString()
        val password = data.optString("password").toString()
        val gender = data.optString("gender").toString()
        val mobile = data.optString("mobile").toString()
        val birthday = data.optString("birthday").toString()
        val integral = data.optString("integral").toInt()
        val balance = data.optString("balance").toString()
        val address = data.optString("address").toString()
        val tid = data.optString("tid").toString()
        editor.putInt("uid", uid)
        editor.putString("username", username)
        editor.putString("password", password)
        editor.putString("gender", gender)
        editor.putString("mobile", mobile)
        editor.putString("birthday", birthday)
        editor.putInt("integral", integral)
        editor.putString("balance", balance)
        editor.putString("address", address)
        editor.putString("tid", tid)
        editor.apply()

    }

    override fun onResume() {
        super.onResume()
        getUser()
    }
}